<template>
  <a-modal title="分类" :width="700" :visible="visible" @ok="submit" @cancel="cancelAdd">
    <a-form :form="form">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="名称">
            <a-input :disabled='priviewflag' v-decorator="['name',{ rules: [{ required: true, message: '请输入名称' }] }]"
              placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="分类">
            <a-select :disabled='priviewflag'  v-decorator="['yaofangtypeid', { rules: [{ required: true, message: '请选择分类！' }] }]"
              placeholder="请选择分类！" show-search style="width: 300px" :default-active-first-option="false"
              :show-arrow="false">
              <a-select-option v-for="(item, index) in typeList" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="剂型">
            <a-select :disabled='priviewflag'  mode="multiple" v-decorator="['jixingids', { rules: [{ required: true, message: '请选择剂型！' }] }]"
              placeholder="请选择剂型！" show-search style="width: 300px" :default-active-first-option="false"
              :show-arrow="false">
              <a-select-option v-for="(item, index) in jxList" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="拼音首字母">
            <a-input :disabled='priviewflag'  v-decorator="['pinyin',{ rules: [{ required: true, message: '请输入拼音首字母' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="中药">
            <a-button type="primary" @click="addZhongyao" v-if="!priviewflag">添加</a-button>
            <table style="width: 100%;">
              <thead class="ant-table-thead">
                <tr>
                  <th>中药</th>
                  <th>重量(单位g)</th>
                  <th v-if="!priviewflag">操作</th>
                </tr>
              </thead>
              <tbody class="ant-table-tbody" v-if="priviewflag">
                <tr v-for="(item,index) in zhongyao" :key='index'>
                  <td>
                    {{item.chinesedrug}}
                  </td>
                  <td>
                    {{item.gram}}
                  </td>
                </tr>
              </tbody>
              <tbody class="ant-table-tbody" v-else>
                <tr v-for="(item,index) in zhongyao" :key='index'>
                  <td>
                    <a-select style="width: 200px;" v-model="item.chinesedrug" placeholder="请选择" show-search
                      :default-active-first-option="false" :show-arrow="false" :filter-option="false"
                      @search="handleSearch" @change="handleZyChange($event,index)">
                      <a-select-option v-for="(item, index) in zyList" :key="item.id" :value="item.name">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </td>
                  <td>
                    <a-input-number style="width: 200px;" v-model="item.gram" :min="0" allow-clear placeholder="请输入" />
                  </td>
                  <td style="text-align: center;cursor: pointer;" @click="deletZhongyao(index)">
                    删除
                  </td>
                </tr>
              </tbody>
            </table>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
  import {
    jixingList,
    yaofangType,
    yaofangAdd,
    yaofangUpdate
  } from '@/api/yaofang'
  import {
    chineseMedicineList
  } from '@/api/medicine'


  import {
    getFormData
  } from '@/utils/aliOss/aliossUpload.js'
  import aliOssConfig from '@/utils/aliOss/config'
  const formItemLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8
    },
  };
  const formTailLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8,
      offset: 4
    },
  };

  export default {
    props: {
      visible: {
        type: Boolean,
        required: true,
      }
    },
    data() {
      return {
        zyList: [],
        zhongyao: [{
          chinesedrugid: '',
          gram: '',
          chinesedrug: ''
        }],
        typeList: [],
        jxList: [],
        checkNick: false,
        formItemLayout,
        formTailLayout,
        form: this.$form.createForm(this),
        loading: false,
        imageUrl: '',
        formData: {},
        aliOssConfig: aliOssConfig,
        id: 0,
        updateflag: false,
        priviewflag: false
      };
    },
    created() {
      this.getJixing()
      this.getType()
    },
    methods: {
      setPreview(val) {
        this.priviewflag = true
        this.updateflag = true
        this.id = val.id
        let jixingList = []
        if (val.Yaofangjixing) {
          val.Yaofangjixing.forEach(res => {
            jixingList.push(res.id)
          })
        }
        this.form.setFieldsValue({
          name: val.name,
          yaofangtypeid: val.yaofangtypeid,
          jixingids: jixingList,
          pinyin: val.pinyin
        })
        this.zhongyao = val.Yaofangdrug
      },
      setUpdate(formValue) {
        this.priviewflag = false
        this.updateflag = true
        this.id = formValue.id
        let jixingList = []
        if (formValue.Yaofangjixing) {
          formValue.Yaofangjixing.forEach(res => {
            jixingList.push(res.id)
          })
        }
        this.form.setFieldsValue({
          name: formValue.name,
          yaofangtypeid: formValue.yaofangtypeid,
          jixingids: jixingList,
          pinyin: formValue.pinyin
        })
        this.zhongyao = formValue.Yaofangdrug
      },

      addZhongyao() {
        this.zhongyao.push({
          chinesedrugid: '',
          gram: '',
          chinesedrug: ''
        })
      },
      deletZhongyao(index) {
        this.zhongyao.splice(index, 1)
      },
      handleSearch(e) {
        chineseMedicineList({
          name: e,
          pageNo: 1,
          pageSize: 20
        }).then(res => {
          if (res.code == 0) {
            this.zyList = res.data.data
          }
        })
      },
      handleZyChange(e, index) {
        this.zyList.forEach(res => {
          if (res.name == e) {
            this.zhongyao[index].chinesedrugid = parseInt(res.id)
          }
        })
      },
      getType() {
        yaofangType().then(res => {
          this.typeList = res.data
        })
      },
      getJixing() {
        jixingList({}).then(res => {
          this.jxList = res.data
        })
      },
      cancelAdd() {
        this.updateflag = false
        this.$emit('cancel', true)
        this.form.resetFields()
        this.imageUrl = ''
        this.zhongyao = []
        this.priviewflag = false
      },

      submit() {
        if (this.priviewflag) {
          this.cancelAdd()
          return
        }
        var that = this
        const {
          form: {
            validateFields
          },
        } = this

        validateFields((errors, values) => {
          if (!errors) {
            let typename = ''
            this.typeList.forEach(v => {
              if (v.id == values.yaofangtypeid) {
                typename = v.name
              }
            })
            if (this.zhongyao.length == 0) {
              this.$message.error('请添加中药列表')
              return
            } else {
              this.zhongyao.forEach(res => {
                res.chinesedrugid = parseInt(res.chinesedrugid)
              })
            }
            values.parameter = JSON.stringify(this.zhongyao)
            values.jixingids = values.jixingids.join(',')
            values.yaofangtype = typename
            if (this.updateflag) {
              values.id = this.id
              yaofangUpdate({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  that.$emit('ok')
                }
              })
            } else {
              yaofangAdd({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  this.zhongyao = []
                  that.$emit('ok')
                }
              })
            }
          }
        })
      },
      beforeUpload(file) {
        this.formData = getFormData()
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('图片最大体积为2MB!')
        }
        return isJpgOrPng && isLt2M
      },
      check() {
        this.form.validateFields(err => {
          if (!err) {
            console.info('success');
          }
        });
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
          return
        }
        console.log(info.file.status)
        if (info.file.status == 'done') {
          this.imageUrl = this.aliOssConfig.uploadUrl + '/' + this.formData.key
          this.loading = false
        }
      },
    },
  };
</script>